package com.zHan.filter;

import com.alibaba.fastjson.JSONObject;
import com.zHan.pojo.Result;
import com.zHan.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义过滤器
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //类型转化
        HttpServletRequest resquest= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //获取请求url
        String url = resquest.getRequestURL().toString();
        log.info("请求路径：{}", url);

        //判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("/login")){
            filterChain.doFilter(resquest,response);
            return;
        }

        //获取请求头中的令牌（token）
        String token = resquest.getHeader("token");
        log.info("从请求头中获取的令牌：{}",token);

        //判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(token)){
            log.info("token不存在");
            Result result = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        //解析token，如果解析失败，返回错误结果（未登录）
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("token解析失败");

            Result result = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        //放行
        filterChain.doFilter(resquest,response);
    }
}
